package com.example.user.login

import androidx.lifecycle.viewModelScope
import com.example.lib_base.entity.LoginEntity
import com.example.lib_base.entity.Res
import com.example.lib_base.entity.SendCodeEntity
import com.example.lib_base.mvvm.BaseViewModel
import com.example.lib_base.utils.SingleLiveData
import com.google.gson.Gson
import kotlinx.coroutines.launch
import okhttp3.MediaType
import okhttp3.MediaType.Companion.toMediaType
import okhttp3.RequestBody

class LoginViewModel:BaseViewModel() {
    val loginSuccess = SingleLiveData<Res<LoginEntity>>()
    val loginFail = SingleLiveData<String>()

    fun login(account:String,password:String){
        viewModelScope.launch {
            try {
                val map = mutableMapOf<String,Any>()
                map["account"] = account
                map["password"] = password
                loginSuccess.postValue(apiService.login(mapToBody(map)))
            } catch (e: Exception) {
                loginFail.postValue(e.message.toString())
            }

        }
    }
    val loginCodeSuccess = SingleLiveData<Res<LoginEntity>>()
    val loginCodeFail = SingleLiveData<String>()
    fun loginCode(captcha:String,phone:String){
        viewModelScope.launch {

            try {
                val map = mutableMapOf<String,Any>()
                map["captcha"] = captcha
                map["phone"] = phone
                loginCodeSuccess.postValue(apiService.loginCode(mapToBody(map)))
            } catch (e: Exception) {
                loginCodeFail.postValue(e.message.toString())
            }
        }

    }





    //发送验证码
    val sendCodeSuccess = SingleLiveData<Res<SendCodeEntity>>()
    val sendCodeFail = SingleLiveData<String>()
    fun sendCode(phone:String){
        viewModelScope.launch {

            try {
                sendCodeSuccess.postValue(apiService.sendCode(phone))
            } catch (e: Exception) {
                sendCodeFail.postValue(e.message.toString())
            }
        }
    }
}